import{Mongoose,Schema,Model,Document} from 'mongoose';
export class DBManager
{
  private static instance:DBManager
  db:Mongoose;
  private modleMap:any = {};
  private constructor(){
    this.db = new Mongoose();
    this.db.connect("mongodb://kinglo:isgeek317@chuxin.fm:27017/kapi");
    this.initMUser();
    this.initMToken();
    this.initMProject();
    this.initMGroup();
    this.initMDoc();
  }

  static getInstance():DBManager{
    if(!this.instance)
    {
      return new DBManager();
    }
    return this.instance;
  }

  getModel(modelName):Model<any>
  {
    return this.modleMap[modelName];
  }

  private initMToken(){
    var schema:Schema = new Schema({
      token:String,
      user:{ type: Schema.Types.ObjectId, ref: 'user' },
      createdAt: { type: Date, default: Date.now }
    });
    var mToken = this.db.model("token",schema);
    this.modleMap["mToken"] = mToken;
  }

  private initMUser(){
    var schema:Schema = new Schema({
      username:String,
      password:String,
      nickname:String,
      avatar:String,
      createdAt: { type: Date, default: Date.now }
    });
    var mUser = this.db.model("user",schema);
    this.modleMap["mUser"] = mUser;
  }

  private initMProject(){
    var schema:Schema = new Schema({
      title:String,
      description:String,
      open:Boolean,
      user:{ type: Schema.Types.ObjectId, ref: 'user' },
      createdAt: { type: Date, default: Date.now }
    });
    var mProject = this.db.model("project",schema);
    this.modleMap["mProject"] = mProject;
  }

  private initMGroup(){
    var schema:Schema = new Schema({
      name:String,
      description:String,
      project:{ type: Schema.Types.ObjectId, ref: 'project' },
      createdAt: { type: Date, default: Date.now }
    });
    var mGroup = this.db.model("group",schema);
    this.modleMap["mGroup"] = mGroup;
  }

  private initMDoc(){
    var schema:Schema = new Schema({
      name:String,
      action:String,
      description:String,
      httpMethod:String,
      url:String,
      params:[{
        name:String,
        description:String,
        paramType:String,
        paramStyle:String,
        optional:Boolean
      }],
      resps:[{
        respCode:String,
        description:String,
        respType:String,
        content:String
      }],
      group:{ type: Schema.Types.ObjectId, ref: 'group' },
      project:{ type: Schema.Types.ObjectId, ref: 'project' },
      createdAt: { type: Date, default: Date.now }
    });
    var mDoc = this.db.model("doc",schema);
    this.modleMap["mDoc"] = mDoc;
  }
}
